package com.lemon.smartsafety.ui.activity.notice;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.address.AddrBookUserVo;
import com.lemon.smartsafety.entity.address.AddrBookVo;
import com.lemon.smartsafety.entity.event.address.AddressBookContactListToWXEvent;
import com.lemon.smartsafety.entity.event.address.AddressRefreshEvent;
import com.lemon.smartsafety.entity.event.address.ContactDeleteEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.AddressBookServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.ui.activity.address.ContractPropActivity;
import com.lemon.smartsafety.ui.activity.address.WXSMSAcitivity;
import com.lemon.smartsafetynew.ui.activity.base.LemonPermissionListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.notice.NoticeContactAdapter;
import com.lemon.smartsafety.ui.widget.IndexView;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class NoticeContactListActivity extends SwipeBackActivity implements RecyclerTClickListener<AddrBookUserVo> {

    private LoggerHelper loggerHelper = new LoggerHelper(NoticeContactListActivity.class);
    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.tv_tip)
    TextView tvTipTop;
    @Bind(R.id.tv_center_tip)
    TextView tvCenterTip;
    @Bind(R.id.index_view)
    IndexView mIndexView;
    @Bind(R.id.float_button)
    FloatingActionButton mFloatButton;
    @Bind(R.id.multiStateView)
    MultiStateView mMultiStateView;


    private NoticeContactAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private List<AddrBookUserVo> mDataList = new ArrayList<>();


    private List<AddrBookUserVo> mBaseDataList = new ArrayList<>();
    private List<AddrBookUserVo> mCheckDataList = new ArrayList<>();
    private List<AddrBookUserVo> sendList = new ArrayList<>();


    private AddrBookVo mBookVo;

    private boolean isCheckWX = false;
    private SelectItemEvent selectItemEvent;

    private int mCurrent_page=1;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            selectItemEvent = (SelectItemEvent) getIntent().getSerializableExtra(BundleKey.NOTICE_CONTACT);
            mBookVo = (AddrBookVo) getIntent().getSerializableExtra(BundleKey.ADDRESS_BOOK_VO);
        }
    }

    @Override
    protected void initTitle() {
        setBarTitle("联系人");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(NoticeContactListActivity.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_address_book_contact_list;
    }

    @Override
    protected void initViews() {
        super.initViews();

        if (null == mBookVo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
            return;
        }
        mFloatButton.setVisibility(View.VISIBLE);

        mAdapter = new NoticeContactAdapter(mDataList, this);
        mMultiStateView.setErrorRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                if (mPullToRefreshRecyclerView != null) {
                    mPullToRefreshRecyclerView.beginRefreshing();
                }
            }
        });


        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.setLayoutManager(mLayoutManager);

        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrent_page=1;
                getNetData();
            }
        });
        mPullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrent_page++;
                getNetData();
            }
        });

        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.beginRefreshing();
        setIndexViewValue();
    }

    private void setIndexViewValue() {
        mPullToRefreshRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                try {
                    if (mAdapter != null && mAdapter.getData().size() != 0) {
                        if (mLayoutManager.findFirstVisibleItemPosition() >= mAdapter.getData().size()) {
                            tvTipTop.setText(mAdapter.getData()
                                    .get(0)
                                    .getIndexCharI());
                        } else {
                            tvTipTop.setText(mAdapter.getData()
                                    .get(mLayoutManager.findFirstVisibleItemPosition())
                                    .getIndexCharI());
                        }
                    } else {
                        tvTipTop.setText("A");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        if (mAdapter != null && mAdapter.getData().size() != 0) {
            tvCenterTip.setText(mAdapter.getData().get(0).getIndexCharI());
        }

        mIndexView.setOnChangedListener(new IndexView.OnChangedListener() {
            @Override
            public void onChanged(String text) {
                int position = mAdapter.getPositionForSection(text.charAt(0));
                if (position != -1) {
                    // position的item滑动到RecyclerView的可见区域，如果已经可见则不会滑动
                    try {
                        mPullToRefreshRecyclerView.smoothScrollToPosition(position+1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //mLayoutManager.scrollToPosition(position);
                }
            }
        });
        mIndexView.setTipTv(tvCenterTip);
    }

    private String getHttpTag() {
        return EventTag.TAG_ADDRESS_BOOK_CONTACT_LIST;
    }


    private void getNetData() {
        AddressBookServices.init().getBookUserList(mBookVo.getBook_id(),mCurrent_page);
    }

    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (getHttpTag().equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                //mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mPullToRefreshRecyclerView.onRefreshComplete();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    httpRefresh((List<AddrBookUserVo>) event.getObj());
                } else {
                    httpRefreshError(event.getMsg());
                }
            }
        } else if (EventTag.TAG_ADDRESS_BOOK_DELETE_CONTACT.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            AddressRefreshEvent refreshEvent = new AddressRefreshEvent();
                            AppService.getBus().post(refreshEvent);
                            getNetData();
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    public void httpRefresh(List<AddrBookUserVo> data) {

        mHUDUtil.hidden();
        if (data != null && !data.isEmpty()) {
            data = AddressBookServices.sortData(data);
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mDataList.clear();
            mDataList.addAll(data);
            mBaseDataList.clear();
            mBaseDataList.addAll(data);
            mAdapter.notifyDataSetChanged();
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }


        mCheckDataList.clear();
        for (AddrBookUserVo addrBookUserVo : mDataList) {
            if (addrBookUserVo.getHasWeixin() != 0) {
                mCheckDataList.add(addrBookUserVo);
            }
        }

    }

    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
    }


    @OnClick({R.id.float_button})
    public void floatButtonAction(View view) {
        Bundle bundle = new Bundle();
        if (mBookVo != null) {
            bundle.putSerializable(BundleKey.ADDRESS_BOOK_VO, mBookVo);
        }
        UIHelper.showActivity(this, bundle, ContractPropActivity.class);
    }


    @Subscribe
    public void onEventMainThread(final AddressRefreshEvent event) {
        getNetData();
    }

    @Subscribe
    public void onEventMainThread(final AddressBookContactListToWXEvent event) {
        Intent intent = new Intent(this, WXSMSAcitivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.ADDRESS_BOOK_WX, (Serializable) sendList);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Subscribe
    public void onEventMainThread(final ContactDeleteEvent event) {
        if (ContactDeleteEvent.class.getName().equals(event.getTag())) {
            getConfirmDialog("是否删除(" + event.getData().getTitleI() + ")？", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        AddressBookServices.init().deleteContact(event.getData().getBook_user_id() + "'");
                    }
                }
            }).show();
        }
    }

    @Override
    public void onItemClick(AddrBookUserVo data, int position) {
        final String phone = StringUtils.nullValue(data.getMobile());
        if (phone.length() == 0) {
            return;
        }

        getConfirmDialog("是否拨打电话：" + phone, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doDialPhone(phone);
                }
            }
        }).show();

    }

    private void doDialPhone(final String phone) {
        checkPermission(getString(R.string.permission_call), new LemonPermissionListener() {
            @Override
            public void onPermissionGranted(int requestCode) {
                Intent phoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                if (ActivityCompat.checkSelfPermission(NoticeContactListActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                NoticeContactListActivity.this.startActivity(phoneIntent);
            }

            @Override
            public void onPermissionDenied(int requestCode, ArrayList<String> deniedPermissions) {
                mHUDUtil.showErrorTip(getString(R.string.permission_denied_action));
            }
        }, Manifest.permission.CALL_PHONE);
    }


    /**
     * 初始化list
     */
    private void initCheckList() {
        if (isCheckWX) {
            mDataList.clear();
            mDataList.addAll(mCheckDataList);
            mAdapter.setCheck(true);
            mAdapter.notifyDataSetChanged();
        } else {
            mDataList.clear();
            mDataList.addAll(mBaseDataList);
            mAdapter.setCheck(false);
            mAdapter.notifyDataSetChanged();
            clearCheckDateList();
        }

    }


    private void clearCheckDateList() {
        for (int i = 0; i < mCheckDataList.size(); i++) {
            mCheckDataList.get(i).setCheck(false);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_wx, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        Log.e("onPrepareOptionsMenu", "onPrepareOptionsMenu");
        menu.clear();
        if (isCheckWX) {
            getMenuInflater().inflate(R.menu.menu_wx_finish, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_wx, menu);
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_wx) {
            //搜索
            if (CommonUtil.listIsEmpty(mDataList)) {
                //ToastUtils.toastMsg("没有有效的数据信息");
            } else {
                isCheckWX = true;
                invalidateOptionsMenu();
                LoggerHelper.error(getClass(), "微信");
                initCheckList();
            }
        }
        if (item.getItemId() == R.id.action_wx_finish) {
            //搜索
            isCheckWX = false;
            invalidateOptionsMenu();
            LoggerHelper.error(getClass(), "微信完成");


            sendList.clear();
            for (AddrBookUserVo addrBookUserVo : mCheckDataList) {
                if (addrBookUserVo.isCheck()) {
                    sendList.add(addrBookUserVo);
                }
            }
            initCheckList();

            if (!CommonUtil.listIsEmpty(sendList)) {
                AppService.getBus().post(new AddressBookContactListToWXEvent());
            }

        }

        return super.onOptionsItemSelected(item);
    }


}
